package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.serivce.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //保存功能
    @PostMapping
    public R save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("保存成功");
    }

    //分页查询
    @GetMapping("page")
    public R page(Integer page, Integer pageSize) {
        Page page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        categoryService.page(page1, wrapper);
        return R.success(page1);
    }

    //更新数据
    @PutMapping
    public R update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //删除分类  要判断是否包含
    @DeleteMapping
    public R delete(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }


    //菜品分类查询
    @GetMapping("list")
            //记得返还集合
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);

    }
}
